<template>
  <EsCubeLoading v-model:visible="initLoading" />

  <div id="preview" class="w-full h-full">
    <n-split
      direction="horizontal"
      :max="0.85"
      :min="0.15"
      :pane1-style="{ display: drawingStore.getIsUploaded ? 'flex' : 'none' }"
      :resize-trigger-size="drawingStore.getIsUploaded ? 3 : 0"
    >
      <template #1 v-if="drawingStore.getIsUploaded">
        <Drawing />
      </template>
      <template #2>
        <div ref="viewportRef" class="relative w-full h-full"></div>

        <PreviewSceneTree />

        <!-- <PreviewOperations class="!hidden" /> -->
        <!-- 法兰信息 -->
        <FlangeProperties />

        <!-- 切换场景 -->
        <div class="floorControl-box !hidden">
          <div class="floor-list-warp">
            <div class="floor-list">
              <div
                @click="handleCheckFloor(f)"
                :class="[
                  'floor',
                  currentFloor == f.value ? 'floor-active' : '',
                ]"
                v-for="f in floorList"
                :key="f.name"
              >
                {{ f.name }}
              </div>
            </div>
          </div>
        </div>
      </template>
    </n-split>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref, onBeforeUnmount } from "vue";
import { useRoute } from "vue-router";
import { t } from "@/language";
import { fetchGetOneScene } from "@/http/api/scenes";
import {
  useDispatchSignal,
  useAddSignal,
  useRemoveSignal,
} from "@/hooks/useSignal";
import { Viewport } from "@/core/preview/Viewport";
import { useSceneInfoStore } from "@/store/modules/sceneInfo";
import { usePreviewOperationStore } from "@/store/modules/previewOperation";
import { useDrawingStore } from "@/store/modules/drawing";
import EsCubeLoading from "@/components/es/EsCubeLoading.vue";
import PreviewSceneTree from "@/views/preview/components/PreviewSceneTree.vue";
import PreviewOperations from "@/views/preview/components/Operations.vue";
import Drawing from "@/components/drawing/Drawing.vue";
import FlangeProperties from "@/components/viewport/FlangeProperties.vue";
import { Storage } from "@/core/Storage";
import { Package } from "@/core/loader/Package";
import { AddObjectCommand } from "@/core/commands/AddObjectCommand";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";

import * as THREE from "three";

const dbStorage = new Storage();

// const route = useRoute();
const sceneInfoStore = useSceneInfoStore();
const operationStore = usePreviewOperationStore();
// 图纸组件相关
const drawingStore = useDrawingStore();

const viewportRef = ref();
const initLoading = ref(true);

const id = useRoute().params.id;

onMounted(async () => {
  window.viewer = new Viewport(viewportRef.value);

  await nextTick();

  //监听视窗变化（节流）
  let timer = null;
  const resizeObserver = new ResizeObserver(() => {
    if (timer) return;
    timer = setTimeout(() => {
      useDispatchSignal(
        "sceneResize",
        viewportRef.value.offsetWidth,
        viewportRef.value.offsetHeight
      );
      timer = null;
    }, 16);
  });
  resizeObserver.observe(viewportRef.value);

  await init(id ? id : "sceneInfo_test_save");
  useAddSignal("objectSelected", objectSelected);
});

async function init(scene_id) {
  /*
  //测试直接加载本地assets文件夹中的scene_demo.json数据场景
// const localJson = (await import("@/assets/sceneAll.json"));
// //   // window.editor.loader.handleJSON(localJson);
// console.log(localJson.default)
//   window.viewer.loadScene(localJson.default);



//   initLoading.value = false;
  

  // window.viewer.modules.roaming.generateColliderEnvironment().then(() => {
  //     // 检查人物模型是否已加载
  //     const checkPlayer = () => {
  //       if (window.viewer.modules.roaming.person !== undefined) {
  //         operationStore.menuList.roaming.loading = false;
  //       } else {
  //         setTimeout(() => {
  //           checkPlayer();
  //         }, 200)
  //       }
  //     }

  //     checkPlayer();
  //   });
  //   window.$message?.success("加载完成！");

  //     useDispatchSignal("sceneLoadComplete");

  //     window.viewer.setup();
  return
*/

  // 获取路由参数
  // const id = route.params.id;
  // if (!id) {
  //   window.$message?.error("参数错误！");
  //   return;
  // }

  // 从本地存储获取场景信息
  const sceneInfo = await dbStorage.getOtherItem(scene_id);
  console.log(sceneInfo);
  if (!sceneInfo) {
    window.$message?.error("获取场景数据失败");
    /*
    window.editor.resource.loadURLTexture(
      `/static/resource/hdr/kloofendal_48d_partly_cloudy_puresky_1k.hdr`,
      (texture) => {
        // 设置贴图映射方式为等距柱状投影反射映射
        texture.mapping = THREE.EquirectangularReflectionMapping;
        // 设置为场景环境贴图
        this.scene.environment = texture;
        // 设置为场景背景
        this.scene.background = texture;

        // 发送场景图变化信号
        useDispatchSignal("sceneGraphChanged");
        window.viewport.render();
      }
    );

    // const model = import();
    // // console.log(model);
    // window.editor.execute(new AddObjectCommand("@/assets/4.glb"));
    // const glbmodel = await import("@/assets/8.glb");
    // window.viewer.loadModel(glbmodel);

    const loader = new GLTFLoader();
    loader.load(
      "/static/model/4.glb",
      (gltf) => {
        console.log(gltf);
        // 加载成功后，将模型添加到场景
        window.editor.execute(new AddObjectCommand(gltf.scene));
      },
      (progress) => {
        // 可选：处理加载进度
        console.log(
          "Loading progress:",
          (progress.loaded / progress.total) * 100 + "%"
        );
      },
      (error) => {
        // 处理加载错误
        console.error("Error loading GLB:", error);
      }
    );
*/
    // const localJson = await import("@/assets/4.json");
    //   // window.editor.loader.handleJSON(localJson);

    // window.viewer.loadScene(localJson.default);

    // initLoading.value = false;
    operationStore.menuList.roaming.loading = false;
    return;
  }

  // 处理cesiumConfig（如果有的话）
  // if (sceneInfo?.cesiumConfig && typeof sceneInfo?.cesiumConfig === 'string') {
  //   sceneInfo?.cesiumConfig = JSON.parse(sceneInfo?.cesiumConfig);
  // }

  // 更新场景信息到store
  sceneInfoStore.setData(sceneInfo);

  initLoading.value = false;
  // 加载场景
  getScene(sceneInfo);
}

//拉取场景
function getScene(sceneInfo) {
  // console.log(sceneInfo);
  // 如果没有主场景key则无场景包
  if (!sceneInfo.zip) {
    window.$message?.warning("该场景为空场景");
    return;
  }

  let notice = window.$notification.info({
    title: "获取场景数据中...",
    content: "请稍后...",
    closable: false,
  });

  // 使用本地存储的解包方法
  window.viewer.modules.package.unpackFromLocalStorage(sceneInfo.zip, {
    onSceneLoad: async (sceneJson, configJson, fromJSONResult) => {
      if (sceneJson.controls?.state) {
        window.viewer.modules.operation.initControlsState =
          sceneJson.controls.state;
      }
      useDispatchSignal("sceneResize");
    },
    onProgress: (progress) => {
      // 显示主场景加载进度
      console.log(`主场景加载进度: ${progress}%`);
    },
    onComplete: () => {
      // 加载完成后，生成Collider环境
      window.viewer.modules.roaming.generateColliderEnvironment().then(() => {
        console.log("----------------------");
        // 检查人物模型是否已加载
        const checkPlayer = () => {
          console.log(window.viewer.modules.roaming.person);
          if (window.viewer.modules.roaming.person !== undefined) {
            operationStore.menuList.roaming.loading = false;
          } else {
            setTimeout(() => {
              checkPlayer();
            }, 200);
          }
        };

        checkPlayer();
      });

      window.$message?.success("加载完成！");

      useDispatchSignal("sceneLoadComplete");

      window.viewer.setup();

      sceneInfoStore.setData(sceneInfo);

      notice.destroy();
    },
  });
}
const currentFloor = ref("All");

// 初始楼层列表，不包含"全部楼层"选项
const floorList = ref([
  {
    value: "floor3",
    name: "F3",
  },
  {
    value: "floor2",
    name: "F2",
  },
  {
    value: "floor1",
    name: "F1",
  },
]);

// 全部楼层选项
const allFloorOption = {
  value: "All",
  name: "全部楼层",
};

const handleCheckFloor = (floor) => {
  console.log(window);
  // 获取场景中的楼层Group
  const floor1 = window.viewer.scene.getObjectByName("floor1.glb");
  const floor2 = window.viewer.scene.getObjectByName("floor2.glb");
  const floor3 = window.viewer.scene.getObjectByName("floor3.glb");

  if (floor.value == "All") {
    // 点击全部楼层，显示所有楼层
    floor1.visible = true;
    floor2.visible = true;
    floor3.visible = true;
    // 移除全部楼层按钮
    floorList.value = floorList.value.filter((f) => f.value != "All");
    currentFloor.value = "All";

    // 聚焦到整个场景

    window.editor.focus(window.viewer.scene);
  } else {
    // 点击单个楼层
    floor1.visible = floor.name == "F1";
    floor2.visible = floor.name == "F2";
    floor3.visible = floor.name == "F3";

    // 获取当前选中的楼层
    const targetFloor =
      floor.name === "F1" ? floor1 : floor.name === "F2" ? floor2 : floor3;
    // window.editor.focus(targetFloor);
    useDispatchSignal("objectFocusedView", targetFloor);
    // 添加全部楼层按钮（如果还没有）
    if (!floorList.value.find((f) => f.value == "All")) {
      floorList.value.push(allFloorOption);
    }
    console.log(floorList.value);
    currentFloor.value = floor.value;
  }
  console.log(window.viewer.scene);
  window.viewer.render();
};

async function smoothLoadScene(sceneInfo) {
  if (!sceneInfo.zip) {
    window.$message?.warning("该场景为空场景");
    return;
  }
  window.viewer.scene.clear();
  let notice = window.$notification.info({
    title: "获取场景数据中...",
    content: "请稍后...",
    closable: false,
  });

  // 1. 创建新的Package实例，避免复用可能导致的问题
  const _package = new Package();

  // 2. 配置场景加载回调
  _package.unpackFromLocalStorage(sceneInfo.zip, {
    onSceneLoad: async (sceneJson, configJson, fromJSONResult) => {
      if (sceneJson.controls?.state) {
        window.viewer.modules.operation.initControlsState =
          sceneJson.controls.state;
      }
      useDispatchSignal("sceneResize");
    },
    onProgress: (progress) => {
      // 显示主场景加载进度
      console.log(`主场景加载进度: ${progress}%`);
    },
    onComplete: () => {
      // 加载完成后，生成Collider环境
      window.viewer.modules.roaming.generateColliderEnvironment().then(() => {
        // 检查人物模型是否已加载
        const checkPlayer = () => {
          if (window.viewer.modules.roaming.person !== undefined) {
            operationStore.menuList.roaming.loading = false;
          } else {
            setTimeout(() => {
              checkPlayer();
            }, 200);
          }
        };

        checkPlayer();
      });

      window.$message?.success("加载完成！");

      useDispatchSignal("sceneLoadComplete");

      window.viewer.setup();

      sceneInfoStore.setData(sceneInfo);

      notice.destroy();
    },
  });
}

async function objectSelected(object) {
  if (!object) {
    return;
  }
  if (object.type == "HtmlSprite") {
    if (object.userData?.scene_id) {
      const scene_id = object.userData.scene_id;
      const sceneInfo = await dbStorage.getOtherItem(scene_id);
      if (!sceneInfo) {
        window.$message?.error("获取场景数据失败");
        return;
      }

      // 更新场景信息到store
      sceneInfoStore.setData(sceneInfo);

      initLoading.value = false;
      await smoothLoadScene(sceneInfo);
      // await init("sceneInfo_test_save_1");
    }
    return;
  } else {
    //如果是点击模型也想跳转
    if (object.parent && object.parent.userData?.scene_id) {
      console.log(object.userData);
      const scene_id = object.parent.userData?.scene_id;
      const sceneInfo = await dbStorage.getOtherItem(scene_id);
      if (!sceneInfo) {
        window.$message?.error("获取场景数据失败");
        return;
      }

      // 更新场景信息到store
      sceneInfoStore.setData(sceneInfo);

      initLoading.value = false;
      await smoothLoadScene(sceneInfo);
    }

    if (object.userData && object.userData?.scene_id) {
      console.log(object.userData);
      const scene_id = object.userData?.scene_id;
      const sceneInfo = await dbStorage.getOtherItem(scene_id);
      if (!sceneInfo) {
        window.$message?.error("获取场景数据失败");
        return;
      }

      // 更新场景信息到store
      sceneInfoStore.setData(sceneInfo);

      initLoading.value = false;
      await smoothLoadScene(sceneInfo);
    }
  }
}

onBeforeUnmount(() => {
  useRemoveSignal("objectSelected", objectSelected);
});
</script>

<style scoped lang="less">
:deep(#es-view-cube-container) {
  display: none;
}

.n-split {
  &-pane-1,
  &-pane-2 {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
  }
}

.floorControl-box {
  position: absolute;
  bottom: 20px;
  left: 20px;
  width: fit-content;
  pointer-events: all;
  display: flex;
  flex-direction: column;
  align-items: center;
  -webkit-user-select: none;
  user-select: none;
  transition-delay: 0s;
  transition: right 0.5s;
  .floor-list-warp {
    height: auto;
    position: relative;
    width: 59px;
    .floor-list {
      position: absolute;
      bottom: 0;
      left: 0;
      transition: 0.2s all;
      .floor {
        width: 59px;
        height: 59px;
        background-image: url("@/assets/images/floor.png");
        background-size: 100% 100%;
        margin-bottom: 13px;
        text-align: center;
        line-height: 59px;
        font-size: 14px;
        font-family: HP;
        color: #fff;
        cursor: pointer;
        &.floor-active {
          background-image: url("@/assets/images/floor-active.png");
        }
      }
    }
  }
}
:deep(.button-plane) {
  cursor: pointer;
}
</style>
